﻿using System;
using System.Linq;
using cludg.Domain.Environment;
using cludg.Repository.NHibernate.Sessions;
using NHibernate.Linq;

namespace cludg.Repository.Environment.NHibernate
{
	public class SettingRepository : ISettingRepository
	{
		protected readonly INHibernateSessionController SessionController;

		public SettingRepository(INHibernateSessionController sessionController)
		{
			SessionController = sessionController;
		}

		public IQueryable<Setting> Get()
		{
			return SessionController.Current.Linq<Setting>(
				SessionController.Current.CreateCriteria<Setting>().SetCacheable(true));
		}

		public Setting ByScopeAndName(SettingScope scope, string name, string userId)
		{
			Setting setting = null;
			if (scope == SettingScope.Global)
			{
				setting = SessionController.Current.Linq<Setting>(
					SessionController.Current.CreateCriteria<Setting>().SetCacheable(true))
					.Where(x => x.Name == name && x.Scope == scope && x.User == null)
					.FirstOrDefault();
			}
			else
			{
				setting = SessionController.Current.Linq<Setting>(
				SessionController.Current.CreateCriteria<Setting>().SetCacheable(true))
				.Where(x => x.Name == name && x.Scope == scope && x.User != null && x.User.Id == userId)
				.FirstOrDefault();
			}
			return setting;
		}

		public void Add(Setting setting)
		{
			try
			{
				SessionController.Current.Save(setting);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}

		public void Save(Setting setting)
		{
			try
			{
				SessionController.Current.Update(setting);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}

		public void Delete(SettingScope scope, string name, string userId)
		{
			Setting setting = ByScopeAndName(scope, name, userId);
			
			if (setting != null)
			{
				try
				{
					SessionController.Current.Delete(setting);
				}
				catch (Exception)
				{
					SessionController.Reset();
					throw;
				}
			}
		}
	}
}
